import requests
import math
import os
import _thread
from delete_301 import is_html
import time


def save_tile(_file_path, _url):
    proxy = {"http": "http://127.0.0.1:1080", "https": "http://127.0.0.1:1080"}
    ir = requests.get(_url, proxies=proxy)
    if ir.status_code == 200:
        open(_file_path, 'wb').write(ir.content)
        if is_html(_file_path):
            os.remove(_file_path)
            print(_file_path, " is html file.")
        print(_url)
    else:
        print("Request ->", _url, "error. path:", _file_path)


if __name__ == '__main__':
    y_start = 0
    x_start = 0
    min_layer = 5
    max_layer = 18
    base_path = "F:\darkmap_tiles"
    url = 'https://tiles.windy.com/tiles/v8.1/darkmap/{z}/{x}/{y}.png'
    for z in range(min_layer, max_layer):
        for y in range(y_start, int(math.pow(2, z) - 1)):
            for x in range(x_start, int(math.pow(2, z) - 1)):
                _dir = os.path.join(os.path.join(base_path, str(z)), str(y))
                if not os.path.exists(_dir):
                    os.makedirs(_dir)
                file_path = os.path.join(_dir, str(x) + ".png")
                if os.path.isfile(file_path):
                    print(file_path, " is existed.")
                    continue
                _url = url.replace("{z}", str(z)).replace("{y}", str(y)).replace("{x}", str(x))
                _thread.start_new_thread(save_tile, (file_path, _url))
                time.sleep(.1)
